# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.


import os
from Environment import SESSION_DIR, COOKIENAME
import ConfigParser

if not os.path.exists(SESSION_DIR):
    SESSION_DIR = "/home/promo/odmc/session"

class Session(object):
    """
    Gestisce le sessioni utente, attraverso il controllo dei cookies di sessione
    """

    def __init__(self, req):
        self.session_dir = SESSION_DIR
        self.req = req
        self.path = req.environ['PATH_INFO'].split('/')

    def start(self, id_user=None, schema=None, id_oper=None):
        """
        Inizializzazione sessione
        """
        from web_lib.webutils import leggiInSessione , salvaInSessione
        if not os.path.exists(self.session_dir):
            os.mkdir(self.session_dir, 02770)
        if not leggiInSessione(sezione="Main", chiave="schema"):
            sid = self.req.cookies[COOKIENAME]
            session_file = self.session_dir + "/" + sid

            config = ConfigParser.RawConfigParser()
            config.add_section('Main')
            config.set('Main', 'id_user', id_user)
            config.set('Main', 'id_oper', id_oper)
            config.set('Main', 'schema', schema)
            with open(session_file, 'wb') as configfile:
                config.write(configfile)
        else:
            salvaInSessione(self.req, sezione="Main", chiave="id_user", valore=id_user)
            salvaInSessione(self.req, sezione="Main", chiave="id_oper", valore=id_oper)

    def destroy(self):
        """ Distruzione sessione """
        sid = self.req.cookies[COOKIENAME]
        session_file = self.session_dir + "/" + sid
        if os.path.exists(session_file):
            os.remove(session_file)

    def control(self):
        """
        Controllo sessione
        """
        if COOKIENAME not in self.req.cookies:
            #print '>>>>>           NON CI SONO COOKIE           <<<<<'
            return False
        else:
            filee = self.req.cookies[COOKIENAME]
            sess_dir = os.listdir(self.session_dir)
            if filee in sess_dir and self.getUserId():
                #print '>>>>>          AUTENTICATO           <<<<<'
                return True
            else:
                #print ">>>>>>      NON AUTENTICATO               <<<<<<"
                return False

    def getUserId(self):
        """
        Legge l'userid dal file di sessione e lo restituisce
        """
        cookiename = COOKIENAME
        if cookiename in self.req.cookies:
            fileee = self.req.cookies[cookiename]
            session_file = self.session_dir + "/" + fileee
            if os.path.exists(session_file):
                config = ConfigParser.RawConfigParser()
                config.read(session_file)
                try:
                    id_user = config.getint('Main', 'id_user')
                    return int(id_user)
                except:
                    return None
            return 0
        else:
            return 0

    def getOperId(self):
        """
        Legge l'userid dal file di sessione e lo restituisce
        """
        cookiename = COOKIENAME
        if cookiename in self.req.cookies:
            fileee = self.req.cookies[cookiename]
            session_file = self.session_dir + "/" + fileee
            if os.path.exists(session_file):
                config = ConfigParser.RawConfigParser()
                config.read(session_file)
                try:
                    id_oper = config.getint('Main', 'id_oper')
                    return int(id_oper)
                except:
                    return None
            return 0
        else:
            return 0
